﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using AutoBuyWinform.entity;
using AutoBuyWinform.service;
using System.Collections;

namespace AutoBuyWinform
{
    public partial class LogForm : Form
    {
        //StringBuilder logText;
        Product product;
        CookieContainer ccEntered;
        Thread t;
        int logLength = 1024;

        ProductConditions productConditions;
        private int searchWaitTime;

        public LogForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 用于购买
        /// </summary>
        /// <param name="product"></param>
        /// <param name="ccEntered"></param>
        public LogForm(Product product, CookieContainer ccEntered)
        {
            InitializeComponent();
            //this.logText = new StringBuilder();
            this.product = product;
            this.ccEntered = ccEntered;
        }

        /// <summary>
        /// 用于扫描产品列表
        /// </summary>
        /// <param name="productConditions"></param>
        /// <param name="ccEntered"></param>
        public LogForm(ProductConditions productConditions, CookieContainer ccEntered)
        {
            InitializeComponent();
            //this.logText = new StringBuilder();
            this.productConditions = productConditions;
            this.ccEntered = ccEntered;
            this.searchWaitTime = Form1.searchWaitTime;
        }

        private void LogForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //e.Cancel = true;
            //this.Hide();
            t.Abort();
        }

        public void startBuy()
        {
            t = new Thread(() =>
            {
                bool success = false;
                PostGoodsToCart pc = new PostGoodsToCart(product, ccEntered);
                success = pc.doPost(this);
                if (!success)
                {
                    this.Invoke(new Action(() =>
                    {
                        this.setMsg("加入购物车失败");
                    }));
                    return;
                }

                //yj_hidden
                //加入购物车成功后，按需进行议价
                /*
                if (product.yj[0] != 0)
                {
                    YjPage yjPage = new YjPage();
                    success = pc.createYj(this, yjPage);
                    if (!success)
                    {
                        this.Invoke(new Action(() =>
                        {
                            this.setMsg("议价生成订单失败");
                        }));
                    }
                    else
                    {
                        this.Invoke(new Action(() =>
                        {
                            this.setMsg("议价生成订单成功！");
                        }));
                    }
                    
                }
                */

                //加入购物车后，按需直接生成订单。如果议价失败也直接生成订单
                if (product.yj[0] == 0 || !success)
                {
                    //成功标志：0失败，1成功，2重新下单
                    int cgbz = 2;
                    while (cgbz == 2)
                    {
                        cgbz = pc.createOrder(this);
                    }
                    if (cgbz==0)
                    {
                        this.Invoke(new Action(() =>
                        {
                            this.setMsg("直接生成订单失败");
                        }));
                        return;
                    }

                    this.Invoke(new Action(() =>
                    {
                        this.setMsg("直接生成订单成功！");
                    }));
                }

                

                Application.Run();
            });
            t.SetApartmentState(ApartmentState.STA);
            t.IsBackground = true;
            t.Start();
            //threadContainer.AddLast(t);
        }

        public void startSearch()
        {
            t = new Thread(() =>
            {
                try
                {
                    DateTime time1 = DateTime.Now;
                    Operations operations = new Operations();
                    int i = 0;
                    ArrayList buyedPackid = new ArrayList();
                    WebForm wf = new WebForm();

                    while (true)
                    {
                        i++;
                        this.Invoke(new Action(() =>
                        {
                            this.Text = "扫描商品 日志窗口（扫描第" + i.ToString() + "遍）";
                        }));
                        Thread.Sleep(searchWaitTime);
                        
                        string msg = operations.searchProducts(this, productConditions, buyedPackid, wf, Util.GetCookieContainerCopy(ccEntered));
                        if (msg != null)
                        {
                            this.Invoke(new Action(() =>
                            {
                                this.setMsg(msg,true);
                            }));
                            break;
                        }
                    }
                    Application.Run();
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.Message+"\n"+ex.StackTrace);
                }

            });
            t.SetApartmentState(ApartmentState.STA);
            t.IsBackground = true;
            t.Start();
            
        }

        public void setMsg(String msg, bool noLengthLimit)
        {
            int length = this.logLength;
            if (noLengthLimit)
            {
                length = int.MaxValue;
            }

            setMsg(msg);
        }

        public void setMsg(String msg)
        {
            logBox.Text = DateTime.Now + ":" + msg + "\r\n" + logBox.Text.Substring(0, logBox.Text.Length > logLength ? logLength : logBox.Text.Length);
            Refresh();
        }

    }
}
